package it.trekker.converter;

import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import it.trekker.dataexchange.PoiRealTimeInfo;
import it.trekker.upload.json.ExcursionAdapter;
import com.google.gson.*;

public class JsonConverter implements IJsonConverter {
	
	private static final String DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss zzz";
//	private static final String DATE_FORMAT = "dd MMM yyyy HH:mm:ss";
	private Gson gson;
	
	public JsonConverter() {
		gson = new GsonBuilder().registerTypeAdapter(Date.class, new DateTypeAdapter()).create();
//		gson = new GsonBuilder().setDateFormat(DATE_FORMAT).create();
//		gson = new Gson();
	}
	
	@Override
	public String PoiRealTimeInfo2Json(PoiRealTimeInfo poi) {
		return gson.toJson(poi);
	}
	
	@Override
	public String PoiRealTimeInfoArray2Json(PoiRealTimeInfo[] pois) {
		return gson.toJson(pois);
	}
	
	@Override
	public PoiRealTimeInfo Json2PoiRealTimeInfo(String json) {
		return gson.fromJson(json, PoiRealTimeInfo.class);
	}
	
	@Override
	public PoiRealTimeInfo[] Json2PoiRealTimeInfoArray(String json) {
		return gson.fromJson(json, PoiRealTimeInfo[].class);
	}
	
	@Override
	public String Excursion2Upload2Json(ExcursionAdapter excursion) {
		return gson.toJson(excursion);
	}
	
	@Override
	public ExcursionAdapter Json2Excursion2Upload(String json) {
		return gson.fromJson(json, ExcursionAdapter.class);
	}
	
	@Override
	public String Excursion2UploadArray2Json(ExcursionAdapter[] excursions) {
		return gson.toJson(excursions);
	}
	
	@Override
	public ExcursionAdapter[] Json2Excursion2UploadArray(String json) {
		return gson.fromJson(json, ExcursionAdapter[].class);
	}
	
	
	
	public class DateTypeAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {

//		private final DateFormat format = DateFormat.getInstance();
		private final SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT);

		@Override
		public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
//			String dateFormatAsString = format.format(src);
			String dateFormatAsString = String.valueOf(src.getTime());
			return new JsonPrimitive(dateFormatAsString);
		}

		@Override
		public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
			if (!(json instanceof JsonPrimitive)) {
				throw new JsonParseException("The date should be a string value");
			}

//			try {
//				return format.parse(json.getAsString());
//			} catch (ParseException e) {
//				throw new JsonParseException(e);
//			}
			return new Date(json.getAsLong());
		}
	}
}
